<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- CSRF元数据 -->
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <meta name="_csrf_parameter" th:content="${_csrf.parameterName}"/>
    <title>哈尔滨双城区农产品物流园管理系统</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <style>
        .content-iframe {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
        .content-iframe iframe {
            width: 100%;
            height: 800px;
            border: none;
            overflow: auto;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <!-- 侧边栏 -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <h3><i class="fas fa-leaf mr-2"></i>哈尔滨双城区物流园管理系统</h3>
            </div>

            <ul class="list-unstyled components">
                <li class="active">
                    <a href="#" onclick="loadContent('dashboard')">
                        <i class="fas fa-tachometer-alt mr-2"></i>控制台
                    </a>
                </li>
                <li>
                    <a href="#warehouseSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                        <i class="fas fa-warehouse mr-2"></i>仓库管理
                    </a>
                    <ul class="collapse list-unstyled" id="warehouseSubmenu">
                        <li>
                            <a href="#" onclick="loadContent('warehouse')">仓库信息</a>
                        </li>
                        <li>
                            <a href="#coldStorageSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                                <i class="fas fa-thermometer-half mr-2"></i>冷库温湿度管理
                            </a>
                            <ul class="collapse list-unstyled" id="coldStorageSubmenu">
                                <li>
                                    <a href="#" onclick="loadContent('coldStorageMonitor')">实时监控</a>
                                </li>
                                <li>
                                    <a href="#" onclick="loadContent('coldStorageHistory')">历史数据</a>
                                </li>
                                <li>
                                    <a href="#" onclick="loadContent('coldStorageTrend')">趋势分析</a>
                                </li>
                                <li>
                                    <a href="#" onclick="loadContent('coldStorageThreshold')">阈值设置</a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#productSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                        <i class="fas fa-box mr-2"></i>产品管理
                    </a>
                    <ul class="collapse list-unstyled" id="productSubmenu">
                        <li>
                            <a href="#" onclick="loadContent('product')">产品信息</a>
                        </li>
                        <li>
                            <a href="#" onclick="loadContent('stock')">库存管理</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#transactionSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                        <i class="fas fa-exchange-alt mr-2"></i>交易管理
                    </a>
                    <ul class="collapse list-unstyled" id="transactionSubmenu">
                        <li>
                            <a href="#" onclick="loadContent('transaction')">交易记录</a>
                        </li>
                        <li>
                            <a href="#" onclick="loadContent('transactionAnalysis')">交易分析</a>
                        </li>
                        <li>
                            <a href="#" onclick="loadContent('transactionReport')">交易报表</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#businessSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                        <i class="fas fa-handshake mr-2"></i>商户与客户管理
                    </a>
                    <ul class="collapse list-unstyled" id="businessSubmenu">
                        <li>
                            <a href="#" onclick="loadContent('business/merchant')">商户管理</a>
                        </li>
                        <li>
                            <a href="#" onclick="loadContent('business/customer')">客户管理</a>
                        </li>
                        <li>
                            <a href="#" onclick="loadContent('business/supplier')">供应商管理</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#financeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                        <i class="fas fa-money-bill-wave mr-2"></i>财务交易
                    </a>
                    <ul class="collapse list-unstyled" id="financeSubmenu">
                        <li>
                            <a href="#" onclick="loadContent('order')">订单管理</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#securitySubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                        <i class="fas fa-shield-alt mr-2"></i>安全管理
                    </a>
                    <ul class="collapse list-unstyled" id="securitySubmenu">
                        <li>
                            <a href="#" onclick="loadContent('inspection')">安全检查</a>
                        </li>
                    </ul>
                </li>
                <li>
                    <a href="#systemSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                        <i class="fas fa-cogs mr-2"></i>系统管理
                    </a>
                    <ul class="collapse list-unstyled" id="systemSubmenu">
                        <li>
                            <a href="#" onclick="loadContent('sysuser')">用户管理</a>
                        </li>
                    </ul>
                </li>
            </ul>

            <div class="sidebar-footer">
                <p>© 2025 哈尔滨双城区农产品物流园管理系统</p>
            </div>
        </nav>

        <!-- 页面内容 -->
        <div id="content">
            <nav class="navbar navbar-expand-lg navbar-light">
                <div class="container-fluid">
                    <button type="button" id="sidebarCollapse" class="btn btn-info">
                        <i class="fas fa-align-left"></i>
                        <span>切换侧边栏</span>
                    </button>

                    <div class="ml-auto">
                        <div class="dropdown">
                            <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="userDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <i class="fas fa-user-circle mr-1"></i>
                                <span id="currentUsername">管理员</span>
                            </button>
                            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown">
                                <a class="dropdown-item" href="#" onclick="loadContent('profile')">
                                    <i class="fas fa-id-card mr-2"></i>个人信息
                                </a>
                                <a class="dropdown-item" href="#" onclick="loadContent('settings')">
                                    <i class="fas fa-cog mr-2"></i>系统设置
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="javascript:void(0);" onclick="logout()">
                                    <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </nav>

            <!-- 主要内容区域 -->
            <div id="mainContent">
                <!-- 控制台内容 -->
                <div class="dashboard-container">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="card text-white bg-primary mb-3">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-3">
                                            <i class="fas fa-warehouse fa-3x"></i>
                                        </div>
                                        <div class="col-9 text-right">
                                            <h3 id="warehouseCount">0</h3>
                                            <div>仓库总数</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer">
                                    <a href="#" class="text-white" onclick="loadContent('warehouse')">
                                        <span class="float-left">查看详情</span>
                                        <span class="float-right"><i class="fas fa-arrow-circle-right"></i></span>
                                        <div class="clearfix"></div>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-white bg-success mb-3">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-3">
                                            <i class="fas fa-box fa-3x"></i>
                                        </div>
                                        <div class="col-9 text-right">
                                            <h3 id="productCount">0</h3>
                                            <div>产品总数</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer">
                                    <a href="#" class="text-white" onclick="loadContent('product')">
                                        <span class="float-left">查看详情</span>
                                        <span class="float-right"><i class="fas fa-arrow-circle-right"></i></span>
                                        <div class="clearfix"></div>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-white bg-warning mb-3">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-3">
                                            <i class="fas fa-shopping-cart fa-3x"></i>
                                        </div>
                                        <div class="col-9 text-right">
                                            <h3 id="orderCount">0</h3>
                                            <div>订单总数</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer">
                                    <a href="#" class="text-white" onclick="loadContent('order')">
                                        <span class="float-left">查看详情</span>
                                        <span class="float-right"><i class="fas fa-arrow-circle-right"></i></span>
                                        <div class="clearfix"></div>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-white bg-danger mb-3">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-3">
                                            <i class="fas fa-exclamation-triangle fa-3x"></i>
                                        </div>
                                        <div class="col-9 text-right">
                                            <h3 id="alertCount">0</h3>
                                            <div>预警总数</div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer">
                                    <a href="#" class="text-white" onclick="loadContent('inspection')">
                                        <span class="float-left">查看详情</span>
                                        <span class="float-right"><i class="fas fa-arrow-circle-right"></i></span>
                                        <div class="clearfix"></div>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="card mb-3">
                                <div class="card-header">
                                    <i class="fas fa-chart-bar mr-1"></i>
                                    月度订单统计
                                </div>
                                <div class="card-body">
                                    <canvas id="orderChart" height="300"></canvas>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card mb-3">
                                <div class="card-header">
                                    <i class="fas fa-chart-pie mr-1"></i>
                                    产品类型分布
                                </div>
                                <div class="card-body">
                                    <canvas id="productChart" height="300"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="card mb-3">
                                <div class="card-header">
                                    <i class="fas fa-table mr-1"></i>
                                    最近订单
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="recentOrdersTable" width="100%" cellspacing="0">
                                            <thead>
                                                <tr>
                                                    <th>订单号</th>
                                                    <th>客户</th>
                                                    <th>金额</th>
                                                    <th>状态</th>
                                                    <th>时间</th>
                                                </tr>
                                            </thead>
                                            <tbody id="recentOrders">
                                                <!-- 这里将通过AJAX加载最近订单数据 -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="card-footer small text-muted">
                                    <a href="#" onclick="loadContent('order')">查看所有订单</a>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card mb-3">
                                <div class="card-header">
                                    <i class="fas fa-bell mr-1"></i>
                                    库存预警
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="stockAlertTable" width="100%" cellspacing="0">
                                            <thead>
                                                <tr>
                                                    <th>产品名称</th>
                                                    <th>仓库</th>
                                                    <th>当前库存</th>
                                                    <th>状态</th>
                                                </tr>
                                            </thead>
                                            <tbody id="stockAlerts">
                                                <!-- 这里将通过AJAX加载库存预警数据 -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="card-footer small text-muted">
                                    <a href="#" onclick="loadContent('stock')">查看所有库存</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <script>
        $(document).ready(function () {
            // 侧边栏切换
            $('#sidebarCollapse').on('click', function () {
                $('#sidebar').toggleClass('active');
            });

            // 初始加载控制台数据
            loadDashboardData();
            
            // 响应式处理：小屏幕自动收起侧边栏
            if ($(window).width() < 768) {
                $('#sidebar').addClass('active');
            }
            
            // 窗口大小变化时的处理
            $(window).resize(function() {
                if ($(window).width() < 768) {
                    $('#sidebar').addClass('active');
                }
            });
            
            // 处理导航菜单的活动状态
            $('.components li a').click(function(){
                $('.components li').removeClass('active');
                $(this).closest('li').addClass('active');
            });
            
            // 加载当前用户信息
            loadCurrentUser();
        });
        
        // 加载控制台数据
        function loadDashboardData() {
            // 使用延迟加载和Promise.all优化数据加载
            setTimeout(function() {
                // 首先加载最重要的统计数据
                loadStatistics();
                
                // 然后使用延迟加载其他数据
                setTimeout(function() {
                    // 并行加载图表数据
                    loadCharts();
                    
                    // 延迟加载订单和库存预警
                    setTimeout(function() {
                        loadRecentOrders();
                        loadStockAlerts();
                    }, 500);
                }, 200);
            }, 100);
        }
        
        // 加载统计数据
        function loadStatistics() {
            // 使用本地缓存检查是否有最近的数据
            const cacheTime = 5 * 60 * 1000; // 5分钟缓存
            const now = new Date().getTime();
            const statsCache = JSON.parse(localStorage.getItem('dashboardStats') || '{}');
            
            if (statsCache.timestamp && (now - statsCache.timestamp < cacheTime)) {
                // 使用缓存数据
                $('#warehouseCount').text(statsCache.warehouseCount || 0);
                $('#productCount').text(statsCache.productCount || 0);
                $('#orderCount').text(statsCache.orderCount || 0);
                $('#alertCount').text(statsCache.alertCount || 0);
                return;
            }
            
            // 使用Promise.all并行请求所有统计数据
            Promise.all([
                $.ajax({url: '/warehouse/count', type: 'GET'}),
                $.ajax({url: '/product/count', type: 'GET'}),
                $.ajax({url: '/finance/order/count', type: 'GET'}),
                $.ajax({url: '/stock/alert/count', type: 'GET'})
            ]).then(function(results) {
                const stats = {
                    timestamp: now,
                    warehouseCount: results[0].code === 200 ? (results[0].data || 0) : 0,
                    productCount: results[1].code === 200 ? (results[1].data || 0) : 0,
                    orderCount: results[2].code === 200 ? (results[2].data || 0) : 0,
                    alertCount: results[3].code === 200 ? (results[3].data || 0) : 0
                };
                
                // 更新UI
                $('#warehouseCount').text(stats.warehouseCount);
                $('#productCount').text(stats.productCount);
                $('#orderCount').text(stats.orderCount);
                $('#alertCount').text(stats.alertCount);
                
                // 保存到缓存
                localStorage.setItem('dashboardStats', JSON.stringify(stats));
            }).catch(function(error) {
                console.error('加载统计数据失败:', error);
            });
        }
        
        // 加载图表数据
        function loadCharts() {
            // 订单柱状图
            $.ajax({
                url: '/finance/order/chart',
                type: 'GET',
                success: function(res) {
                    if (res.code === 200) {
                        renderOrderChart(res.data);
                    }
                }
            });
            
            // 产品饼图
            $.ajax({
                url: '/product/chart',
                type: 'GET',
                success: function(res) {
                    if (res.code === 200) {
                        renderProductChart(res.data);
                    }
                }
            });
        }
        
        // 渲染订单柱状图
        function renderOrderChart(data) {
            var ctx = document.getElementById('orderChart').getContext('2d');
            
            // 如果没有数据，使用模拟数据
            if (!data || !data.labels || data.labels.length === 0) {
                data = {
                    labels: ['一月', '二月', '三月', '四月', '五月', '六月'],
                    datasets: [
                        {
                            label: '订单数量',
                            backgroundColor: 'rgba(78, 115, 223, 0.5)',
                            borderColor: 'rgba(78, 115, 223, 1)',
                            borderWidth: 1,
                            data: [15, 22, 18, 24, 33, 28]
                        },
                        {
                            label: '订单金额(千元)',
                            backgroundColor: 'rgba(28, 200, 138, 0.5)',
                            borderColor: 'rgba(28, 200, 138, 1)',
                            borderWidth: 1,
                            data: [25, 32, 28, 36, 45, 52]
                        }
                    ]
                };
            }
            
            new Chart(ctx, {
                type: 'bar',
                data: data,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        }
        
        // 渲染产品饼图
        function renderProductChart(data) {
            var ctx = document.getElementById('productChart').getContext('2d');
            
            // 如果没有数据，使用模拟数据
            if (!data || !data.labels || data.labels.length === 0) {
                data = {
                    labels: ['谷物', '蔬菜', '水果', '肉类', '水产', '乳制品'],
                    datasets: [{
                        data: [25, 20, 15, 18, 12, 10],
                        backgroundColor: [
                            '#4e73df',
                            '#1cc88a',
                            '#36b9cc',
                            '#f6c23e',
                            '#e74a3b',
                            '#6f42c1'
                        ]
                    }]
                };
            }
            
            new Chart(ctx, {
                type: 'pie',
                data: data,
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
        
        // 加载最近订单
        function loadRecentOrders() {
            $.ajax({
                url: '/finance/order/recent',
                type: 'GET',
                data: {
                    limit: 5
                },
                success: function(res) {
                    if (res.code === 200) {
                        renderRecentOrders(res.data);
                    }
                }
            });
        }
        
        // 渲染最近订单
        function renderRecentOrders(data) {
            let html = '';
            
            // 如果没有数据，使用模拟数据
            if (!data || data.length === 0) {
                data = [
                    { orderNo: 'O202305001', customerName: '张三', totalAmount: 2500, orderStatus: 'completed', createTime: '2023-05-15 14:30:00' },
                    { orderNo: 'O202305002', customerName: '李四', totalAmount: 1800, orderStatus: 'processing', createTime: '2023-05-16 10:15:00' },
                    { orderNo: 'O202305003', customerName: '王五', totalAmount: 3200, orderStatus: 'pending', createTime: '2023-05-17 09:45:00' }
                ];
            }
            
            data.forEach(function(item) {
                // 设置订单状态样式和文本
                let statusClass = '';
                let statusText = '';
                
                switch (item.orderStatus) {
                    case 'pending':
                        statusClass = 'badge badge-primary';
                        statusText = '待处理';
                        break;
                    case 'processing':
                        statusClass = 'badge badge-warning';
                        statusText = '处理中';
                        break;
                    case 'completed':
                        statusClass = 'badge badge-success';
                        statusText = '已完成';
                        break;
                    case 'cancelled':
                        statusClass = 'badge badge-danger';
                        statusText = '已取消';
                        break;
                    default:
                        statusClass = 'badge badge-secondary';
                        statusText = '未知';
                }
                
                html += `<tr>
                    <td>${item.orderNo}</td>
                    <td>${item.customerName}</td>
                    <td>¥${parseFloat(item.totalAmount).toFixed(2)}</td>
                    <td><span class="${statusClass}">${statusText}</span></td>
                    <td>${item.createTime}</td>
                </tr>`;
            });
            
            $('#recentOrders').html(html);
        }
        
        // 加载库存预警
        function loadStockAlerts() {
            $.ajax({
                url: '/stock/alerts',
                type: 'GET',
                data: {
                    limit: 5
                },
                success: function(res) {
                    if (res.code === 200) {
                        renderStockAlerts(res.data);
                    }
                }
            });
        }
        
        // 渲染库存预警
        function renderStockAlerts(data) {
            let html = '';
            
            // 如果没有数据，使用模拟数据
            if (!data || data.length === 0) {
                data = [
                    { productName: '大米', warehouseName: '1号仓', quantity: 5, unit: 't', status: 'low' },
                    { productName: '苹果', warehouseName: '冷藏仓', quantity: 3, unit: 't', status: 'low' },
                    { productName: '牛肉', warehouseName: '冷冻仓', quantity: 0, unit: 't', status: 'empty' }
                ];
            }
            
            data.forEach(function(item) {
                // 设置状态样式和文本
                let statusClass = '';
                let statusText = '';
                
                switch (item.status) {
                    case 'low':
                        statusClass = 'badge badge-warning';
                        statusText = '库存不足';
                        break;
                    case 'expiring':
                        statusClass = 'badge badge-danger';
                        statusText = '即将过期';
                        break;
                    case 'empty':
                        statusClass = 'badge badge-danger';
                        statusText = '库存耗尽';
                        break;
                    default:
                        statusClass = 'badge badge-secondary';
                        statusText = '未知';
                }
                
                html += `<tr>
                    <td>${item.productName}</td>
                    <td>${item.warehouseName}</td>
                    <td>${item.quantity} ${item.unit}</td>
                    <td><span class="${statusClass}">${statusText}</span></td>
                </tr>`;
            });
            
            $('#stockAlerts').html(html);
        }
        
        // 加载内容页面
        function loadContent(page) {
            // 隐藏控制台
            $('.dashboard-container').hide();
            
            if (page === 'dashboard') {
                // 显示控制台，刷新数据
                $('.dashboard-container').show();
                loadDashboardData();
                return;
            }
            
            // 清空主内容区域并添加加载提示
            $('#mainContent').html('<div class="d-flex justify-content-center mt-5"><div class="spinner-border text-primary" role="status"><span class="sr-only">加载中...</span></div></div>');
            
            // 加载对应页面
            let url = '';
            switch (page) {
                case 'warehouse':
                    url = '/warehouse/index';
                    break;
                case 'coldStorageMonitor':
                    url = '/warehouse/coldStorageMonitor/index';
                    break;
                case 'coldStorageHistory':
                    url = '/warehouse/coldStorageMonitor/history';
                    break;
                case 'coldStorageTrend':
                    url = '/warehouse/coldStorageMonitor/trend';
                    break;
                case 'coldStorageThreshold':
                    url = '/warehouse/coldStorageThreshold/index';
                    break;
                case 'product':
                    url = '/product/index';
                    break;
                case 'stock':
                    url = '/stock/index';
                    break;
                case 'transaction':
                    url = '/transaction/index';
                    break;
                case 'transactionAnalysis':
                    url = '/transaction/analysis';
                    break;
                case 'transactionReport':
                    url = '/transaction/report';
                    break;
                case 'business/merchant':
                    url = '/business/merchant';
                    break;
                case 'business/customer':
                    url = '/business/customer';
                    break;
                case 'business/supplier':
                    url = '/business/supplier';
                    break;
                case 'order':
                    url = '/finance/order/index';
                    break;
                case 'inspection':
                    url = '/security/inspection/index';
                    break;
                case 'sysuser':
                    url = '/system/user/index';
                    break;
                case 'profile':
                    url = '/system/profile';
                    break;
                case 'settings':
                    url = '/system/settings';
                    break;
                default:
                    url = '/dashboard';
            }
            
            // 使用AJAX加载内容
            $.ajax({
                url: url,
                type: 'GET',
                success: function(response) {
                    $('#mainContent').html(response);
                    
                    // 检查是否需要加载特定的脚本
                    if (page.startsWith('business/')) {
                        // 确保Bootstrap Table已正确加载
                        if (typeof $.fn.bootstrapTable === 'undefined') {
                            console.log('Loading Bootstrap Table plugin...');
                            loadScript('https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/bootstrap-table.min.js', function() {
                                loadScript('https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/locale/bootstrap-table-zh-CN.min.js', function() {
                                    // 重新调用初始化函数
                                    setTimeout(initPageScripts, 100);
                                });
                            });
                        } else {
                            // 如果已加载，直接初始化页面中的表格
                            initPageScripts();
                        }
                    }
                },
                error: function(xhr, status, error) {
                    $('#mainContent').html('<div class="alert alert-danger mt-3">加载内容失败: ' + error + '</div>');
                }
            });
        }
        
        // 动态加载脚本
        function loadScript(url, callback) {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;
            script.onload = callback;
            document.head.appendChild(script);
        }
        
        // 初始化页面中的脚本
        function initPageScripts() {
            // 触发页面中的初始化函数
            if ($('#bootstrap-table').length > 0) {
                // 确保bootstrap-table已加载
                if (typeof $.fn.bootstrapTable === 'undefined') {
                    console.log('Loading Bootstrap Table plugin...');
                    loadScript('https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/bootstrap-table.min.js', function() {
                        loadScript('https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/locale/bootstrap-table-zh-CN.min.js', function() {
                            // 重新调用初始化函数
                            setTimeout(initPageScripts, 100);
                        });
                    });
                    return;
                }
                
                // 检查页面上下文
                if (window.location.href.indexOf('merchant') > -1) {
                    if (typeof initMerchantTable === 'function') {
                        initMerchantTable();
                    } else {
                        // 手动触发页面中的ready事件
                        $(document).trigger('ready');
                    }
                } else if (window.location.href.indexOf('customer') > -1) {
                    if (typeof initCustomerTable === 'function') {
                        initCustomerTable();
                    } else {
                        // 手动触发页面中的ready事件
                        $(document).trigger('ready');
                    }
                } else if (window.location.href.indexOf('supplier') > -1) {
                    if (typeof initSupplierTable === 'function') {
                        initSupplierTable();
                    } else {
                        // 手动触发页面中的ready事件
                        $(document).trigger('ready');
                    }
                } else {
                    // 手动触发页面中的ready事件
                    $(document).trigger('ready');
                }
            }
        }
        
        // 加载当前用户信息
        function loadCurrentUser() {
            $.ajax({
                url: '/system/user/info',
                type: 'GET',
                success: function(res) {
                    if (res.code === 200 && res.data) {
                        $('#currentUsername').text(res.data.userName || '管理员');
                    }
                }
            });
        }
        
        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                // 创建表单提交logout请求
                var form = document.createElement('form');
                form.method = 'POST';
                form.action = '/logout';
                
                // 添加CSRF令牌
                var csrfToken = document.createElement('input');
                csrfToken.type = 'hidden';
                csrfToken.name = document.querySelector('meta[name="_csrf_parameter"]').getAttribute('content');
                csrfToken.value = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                form.appendChild(csrfToken);
                
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html> 